package com.fingard.dsp.bank.directbank.sr11;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBatRecRefund;
import com.fingard.dsp.bank.reqrespobj.batrecrefund.ReqBatRecRefund;
import com.fingard.dsp.bank.reqrespobj.batrecrefund.ReqQryBatRecRefund;
import com.fingard.dsp.bank.reqrespobj.batrecrefund.RetAtsBatRecRefund;
import com.fingard.dsp.bank.reqrespobj.batrecrefund.RetAtsQryBatRecRefund;
import com.fingard.dsp.bank.reqrespobj.batrecrefund.detail.RetAtsBatRecRefundDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;

/**
 * 京东N22平台退保
 * 
 * @author Cruise
 * @date 2019/4/24
 */
public class SR11BatRecRefund extends SR11Base implements IBatRecRefund {
	@Override
	public RetAtsBatRecRefund submitBatRecRefund(ReqBatRecRefund p_reqBatRef) throws Exception {
		RetAtsBatRecRefund retAts = new RetAtsBatRecRefund(p_reqBatRef.reqHeader);
		
		try {
			Map<String, Object> bizContent = new HashMap<String, Object>();
			JSONObject head = new JSONObject();
			/* 交易流水号 */
			head.put("TransNo", p_reqBatRef.reqBatchNO);
			/* 数据格式 */
			head.put("DataType", "02");
			/* 渠道划分 */
			head.put("SaleChnl", "01");
			/* 业务操作类型 */
			head.put("BusiType", "01");// 01:通知推送 02:资金通知查询
			/* 交易时间 */
			head.put("TransTime", Format.DateTime14Format.format(new Date()));
			/* 操作人 */
			head.put("Operator", "wxnb001");

			bizContent.put("Header", head);

			JSONObject detailJSONObject = new JSONObject();

			JSONArray detailJsonArray = new JSONArray();

			// 流水映射文件内容
			StringBuilder seqNoMappingContent = new StringBuilder();
			while (p_reqBatRef.readRecord()) {
				String transNo = p_reqBatRef.readedDetail.srcNoteCode;
				JSONObject detail = new JSONObject();

				/* 划账金额 */
				detail.put("PayMoney", p_reqBatRef.readedDetail.payAmount);
				/* 保全受理号 */
				detail.put("EdorAccNo", p_reqBatRef.readedDetail.srcNoteCode);

				detailJsonArray.add(detail);

				if (seqNoMappingContent.length() > 0) {
					seqNoMappingContent.append("\r\n");
				}
				seqNoMappingContent.append(p_reqBatRef.readedDetail.askNumber).append(",").append(transNo);
			}

			WriteBankLogLn2("退保流水映射文件内容:\r\n" + seqNoMappingContent.toString());
			// 退保流水映射存入本地
			Date tmpDateNow = new Date();
			String refundSeqNoPath = getDataFileDirectory(tmpDateNow) + File.separator + p_reqBatRef.reqBatchNO + ".txt";
			WriteBankLogLn2("退保流水映射文件路径:\r\n" + refundSeqNoPath);
			FileHelper.writeFile(refundSeqNoPath, seqNoMappingContent.toString(), getCharset());

			detailJSONObject.put("PolicyInfoList", detailJsonArray);
			bizContent.put("Request", detailJSONObject);

			String p_reqStr = JSON.toJSONString(bizContent);
			String tmpStrRet = sendPostJsonRequest(p_reqStr);

			JSONObject respBizContent = JSON.parseObject(tmpStrRet);
			
			JSONObject respJsonHeader = respBizContent.getJSONObject("Header");
			JSONObject respJsonBody = respBizContent.getJSONObject("Response");
			String respCode = respJsonHeader.getString("ResponseCode");
			if ("Y".equals(respCode)) {
				retAts.respCode = "0";
				retAts.respInfo = respJsonBody.getString("ResultReason");
				retAts.payInfoCode = respJsonBody.getString("ResultReason");
				retAts.transState = respJsonBody.getString("ResultCode");
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = respJsonHeader.getString("ErrorMessage");
			}
		} catch (Exception e) {
			retAts.respCode = "-1";
			retAts.respInfo = e.getMessage();
			e.printStackTrace();
		}

		retAts.writeRetToATS();
		return retAts;
	}

	@Override
	public RetAtsQryBatRecRefund queryBatRecRefund(ReqQryBatRecRefund p_reqQryBatRef) throws Exception {
		RetAtsQryBatRecRefund retAts = new RetAtsQryBatRecRefund(p_reqQryBatRef.reqHeader);
		retAts.reqSeqID = p_reqQryBatRef.reqBatchNO;
		
		try {
			Map<String, Object> bizContent = new HashMap<String, Object>();
			JSONObject head = new JSONObject();
			/* 交易流水号 */
			head.put("TransNo", p_reqQryBatRef.reqHeader.reqSeqID);
			/* 数据格式 */
			head.put("DataType", "02");
			/* 渠道划分 */
			head.put("SaleChnl", "01");
			/* 业务操作类型 */
			head.put("BusiType", "02");// 01:通知推送 02:资金通知查询
			/* 交易时间 */
			head.put("TransTime", Format.DateTime14Format.format(new Date()));
			/* 操作人 */
			head.put("Operator", "wxnb001");

			bizContent.put("Header", head);

			JSONObject detailJSONObject = new JSONObject();

			JSONArray detailJsonArray = new JSONArray();

			String[] tmpSeqNoArray = null;
			File refundSeqNoDir = new File(getDataFileDirectory(p_reqQryBatRef.getBgnDateTime()));
			if (refundSeqNoDir.exists()) {
				File[] refundSeqNoFileList = refundSeqNoDir.listFiles();
				for (File refundSeqNoFile : refundSeqNoFileList) {
					if (refundSeqNoFile.getName().contains(p_reqQryBatRef.reqBatchNO)) {
						// 1、读取本地退保流水映射文件
						String tmpSeqNoContent = FileHelper.readFileText(refundSeqNoFile.getPath(), getCharset());
						if (StringHelper.isNullOrEmpty(tmpSeqNoContent)) {
							retAts.respCode = "-1";
							retAts.respInfo = "退保流水映射文件内容为空!";
							retAts.writeAfterDetail();
							return retAts;
						}
						tmpSeqNoArray = tmpSeqNoContent.split("\r\n");
						String[] tmpSeqArr = new String[tmpSeqNoArray.length];
						int i = 0;
						for (String tmpSeqNo : tmpSeqNoArray) {
							if ((tmpSeqNo.length() > 0)) {
								tmpSeqArr[i] = tmpSeqNo.split(",")[1];
								i++;
								/* 保全受理号 */
								String transNo = tmpSeqNo.split(",")[1];
								JSONObject detail = new JSONObject();
								detail.put("EdorAccNo", transNo);
								detailJsonArray.add(detail);
							}
						}
					}
				}
			}

			detailJSONObject.put("PolicyInfoList", detailJsonArray);
			bizContent.put("Request", detailJSONObject);

			String p_reqStr = JSON.toJSONString(bizContent);
//			String tmpStrRet = "{\"Response\":{\"PolicyInfoList\":[{\"ResultReason\":\"\",\"EdorAccNo\":\"86110120190420001126\",\"ResultCode\":\"Y\"},{\"ResultReason\":\"暂未收到京东划拨通知，请稍后重试\",\"EdorAccNo\":\"86110120190420001127\",\"ResultCode\":\"N\"},{\"ResultReason\":\"暂未收到京东划拨通知，请稍后重试\",\"EdorAccNo\":\"86110120190420001131\",\"ResultCode\":\"N\"},{\"ResultReason\":\"暂未收到京东划拨通知，请稍后重试\",\"EdorAccNo\":\"86110120190420001113\",\"ResultCode\":\"N\"}]},\"Header\":{\"TransNo\":\"19042401903196\",\"TransTime\":\"2019-04-24 18:13:27\",\"ResponseCode\":\"Y\",\"ErrorMessage\":\"成功\",\"Operator\":\"wxnb001\"}}";
			String tmpStrRet = sendPostJsonRequest(p_reqStr);
			JSONObject respBizContent = JSON.parseObject(tmpStrRet);

			JSONObject respJsonObject = respBizContent.getJSONObject("Header");
			JSONObject respBodyJson = respBizContent.getJSONObject("Response");
			String respCode = respJsonObject.getString("ResponseCode");
			if ("Y".equals(respCode)) {
				retAts.respCode = "0";
				JSONArray respdetJsonArray = respBodyJson.getJSONArray("PolicyInfoList");
				
				for(int i =0;i< respdetJsonArray.size();i++) {
					JSONObject respdetJsonArr = (JSONObject) respdetJsonArray.get(i);
					RetAtsBatRecRefundDetail tmpRetDetail = new RetAtsBatRecRefundDetail();
					
					for(String seqNo : tmpSeqNoArray) {
						String[] tmpSeqNo = seqNo.split(",");
						if (tmpSeqNo[1].equals(respdetJsonArr.getString("EdorAccNo"))) {
							tmpRetDetail.askNumber = tmpSeqNo[0];
							
							String transState = respdetJsonArr.getString("ResultCode");
							tmpRetDetail.result = transState;
							if ("Y".equals(transState)) {
								tmpRetDetail.payInfoCode = "成功";
							} else {
								tmpRetDetail.payInfoCode = respdetJsonArr.getString("ResultReason");
							}
				        	retAts.writeRetDetail(tmpRetDetail);
						}
					}
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = respJsonObject.getString("ErrorMessage");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.writeAfterDetail();
		return retAts;
	}
}
